<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends My_Model {
	var	$tableName			= 'users';

    function __construct()
    {
        parent::__construct();
		$this->load->database();
    }

	function findByUserName($username=null){
		if(!empty($username)){
			$where = array('username'=>$username);
			$query = $this->db->get_where($this->tableName,$where);
			$rs = $query->result();
			return empty($rs)?null:$rs[0];
		}
		return null;
	}
	
	function findByUserId($userId=0){
		$userId = empty($userId) ? $this->_data['id'] : $userId;
		
		if(!empty($userId)){
			$where = array('id'=>$userId);
			$query = $this->db->get_where($this->tableName,$where);
			$rs = $query->result_array();
			if(isset($rs[0])) return $rs[0];
		} 
		return null;
	} 
	
	function findByUserEmail($username=null){
		if(!empty($username)){
			$where = array('email'=>$username);
			$query = $this->db->get_where($this->tableName,$where);
			$rs = $query->result();
			return empty($rs)?null:$rs[0];
		}
		return null;
	}
	
	function findAll(){
		$query = $this->db->get($this->_table);
		$rs = $query->result_array();
		return $rs;
	}

	/**
	 * 执行登录
	 * 
	 * @param string $user
	 * @param string $pwd
	 * @return mix $user or false
	 */
	function doLogin($userName,$pwd,$isadmin=false){
		$user	= $this->findByUserEmail($userName);
		if(empty($user)){
			$this->_error = 'error_user_noexists';
			return false;
		}
		if($user->hashed_password!=crypt(trim($pwd),$user->salt)){
			$this->_error = 'error_pwd_wrong';
			return false;
		}
		if($user->is_locked){
			$this->_error = 'error_user_islocked';
			return false;
		}
		//后台登陆验证是否管理员,前台不验证
		if($isadmin && !($user->is_admin)){
			$this->_error = 'error_user_isadmin';
			return false;
		}
		return $user;
	}
	
	function doLoginByUserName($userName,$pwd,$isadmin=false) {
		$user	= $this->findByUserName($userName);
		if(empty($user)){
			$this->_error = 'error_user_noexists';
			return false;
		}
		if($user->hashed_password!=crypt(trim($pwd),$user->salt)){
			$this->_error = 'error_pwd_wrong';
			return false;
		}
		if($user->is_locked){
			$this->_error = 'error_user_islocked';
			return false;
		}
		//后台登陆验证是否管理员,前台不验证
		if($isadmin && !($user->is_admin)){
			$this->_error = 'error_user_isadmin';
			return false;
		}
		return $user;
	}

	function save($user) {
		if (isset($user['password'])) {
			$user['salt']	=  random(6);
			$user['hashed_password'] = crypt($user['password'],$user['salt']);
		}
		return parent::save($user);
	}
}
?>